package org.yscz.task;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.yscz.media.MediaService;

import java.io.File;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class AsyncTasks {

    @Value("${yscz.pictures.abnormal.location}")
    private String abnormalLocation;

    @Autowired
    private MediaService mediaService;

    /**
     * 异步保存告警图片
     * @param alarmImagesList
     */
    @Async
    public void saveCacheImageAsyc(List<AbnormalEmotion> alarmImagesList){
        try {
            log.info("alarmImagesList: [{}]", JSONObject.toJSONString(alarmImagesList));
            File file = new File(abnormalLocation);
            if(!file.exists()) {
                file.mkdirs();
            }
            for (AbnormalEmotion abnormalEmotion : alarmImagesList){
                String imageUid = abnormalEmotion.getImageName();
                Long timeStamp = abnormalEmotion.getTimeStamp();

                String alarmImagePath = abnormalLocation + System.getProperty("file.separator") + imageUid + "_" + timeStamp + ".jpg";
                if(abnormalLocation.endsWith("\\")) {
                    alarmImagePath = abnormalLocation + imageUid + "_" + timeStamp + ".jpg";
                }
                if(imageUid != null){
                    mediaService.saveCacheImage(imageUid, alarmImagePath);
                }
            }
        }catch (Exception e){
            log.error("saveCacheImageAsyc fail  e: "  + e.getMessage());
        }finally {
            alarmImagesList.clear();
        }
    }


}
